document.addEventListener('DOMContentLoaded', function() {
    // DOM元素
    const chatMessages = document.getElementById('chatMessages');
    const userInput = document.getElementById('userInput');
    const sendButton = document.getElementById('sendButton');
    const statusIndicator = document.getElementById('statusIndicator');
    
    // 标签页元素
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');
    
    // 辅助面板元素
    const assistantPanel = document.getElementById('assistantPanel');
    const togglePanel = document.getElementById('togglePanel');
    
    // 内容区域
    const streamContent = document.getElementById('streamContent');
    const nodesContent = document.getElementById('nodesContent');
    const dataContent = document.getElementById('dataContent');
    const chartContent = document.getElementById('chartContent');
    const sqlContent = document.getElementById('sqlContent');
    
    // 信息面板
    const databaseName = document.getElementById('databaseName');
    const businessTypes = document.getElementById('businessTypes');
    const isDataQuery = document.getElementById('isDataQuery');
    const tableCount = document.getElementById('tableCount');
    
    // 检查必要的DOM元素是否存在
    if (!chatMessages || !userInput || !sendButton) {
        console.error('必要的DOM元素未找到，请检查HTML结构');
        return;
    }
    
    // 状态管理
    let isProcessing = false;
    let chartInstances = new Map();
    let currentData = null;
    let currentSql = '';
    let currentChart = null;
    let nodeFlow = [];
    let currentNode = null;
    let currentTypingAnimation = null; // 当前正在进行的打字动画
    
    // 标签页切换
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const tabName = button.dataset.tab;
            
            // 更新按钮状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            
            // 更新内容显示
            tabContents.forEach(content => {
                content.classList.remove('active');
                if (content.id === tabName + 'Tab') {
                    content.classList.add('active');
                }
            });
        });
    });
    
    // 辅助面板折叠功能
    if (togglePanel) {
        togglePanel.addEventListener('click', () => {
            assistantPanel.classList.toggle('collapsed');
        });
    }
    
    // 复制SQL按钮
    const copySqlBtn = document.getElementById('copySqlBtn');
    if (copySqlBtn) {
        copySqlBtn.addEventListener('click', () => {
            if (currentSql) {
                navigator.clipboard.writeText(currentSql).then(() => {
                    showNotification('SQL已复制到剪贴板', 'success');
                }).catch(() => {
                    showNotification('复制失败', 'error');
                });
            }
        });
    }
    
    // 发送消息
    async function sendMessage() {
        const message = userInput.value.trim();
        if (!message || isProcessing) return;
        
        isProcessing = true;
        updateStatus('处理中', 'processing');
        sendButton.disabled = true;
        
        // 添加用户消息
        addMessage(message, 'user');
        userInput.value = '';
        
        // 创建AI消息容器并显示思考动画
        let messageDiv = createAIMessage();
        updateAIMessage(messageDiv, '正在思考...');
        
        // 添加打字动画
        addTypingAnimation(messageDiv);
        
        // 清空之前的内容
        clearAllContent();
        
        try {
            // 连接到Spring AI Alibaba Graph API
            const apiUrl = buildApiUrl(message);
            
            // 使用fetch API进行带认证头的流式请求
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: API_CONFIG.headers
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let aiResponse = '';
            let messageDiv = null;
            let isFirstChunk = true;
            let buffer = '';
            
            // 处理流式数据
            while (true) {
                const { done, value } = await reader.read();
                
                if (done) {
                    updateStatus('完成', 'ready');
                    break;
                }
                
                // 解码数据
                buffer += decoder.decode(value, { stream: true });
                
                // 按行分割数据
                const lines = buffer.split('\n');
                buffer = lines.pop(); // 保留最后一个不完整的行
                
                for (const line of lines) {
                    if (line.trim() === '') continue;
                    
                    try {
                        // 解析流式数据
                        const data = parseStreamData(line);
                        
                        // 显示流式数据
                        displayStreamData(data);
                        
                        // 处理AI回复
                        if (data.answer) {
                            // 移除思考动画
                            removeTypingAnimation(messageDiv);
                            
                            if (isFirstChunk) {
                                // 更新现有消息而不是创建新消息
                                updateAIMessage(messageDiv, '');
                                isFirstChunk = false;
                            }
                            aiResponse += data.answer;
                            appendToAIMessage(messageDiv, data.answer);
                        }
                        
                        // 处理其他字段 - 只有在数据有效时才处理
                        if (data && typeof data === 'object' && !data.raw) {
                            // 如果有任何有效数据，移除思考动画
                            if (isFirstChunk) {
                                removeTypingAnimation(messageDiv);
                                isFirstChunk = false;
                            }
                            processStreamFields(data, messageDiv);
                        }
                        
                    } catch (e) {
                        console.error('解析流式数据出错:', e);
                    }
                }
            }
            
            // 处理最后一行数据
            if (buffer.trim()) {
                try {
                    const data = parseStreamData(buffer);
                    displayStreamData(data);
                    if (data.answer) {
                        // 移除思考动画
                        removeTypingAnimation(messageDiv);
                        
                        if (isFirstChunk) {
                            updateAIMessage(messageDiv, '');
                            isFirstChunk = false;
                        }
                        aiResponse += data.answer;
                        appendToAIMessage(messageDiv, data.answer);
                    }
                    processStreamFields(data, messageDiv);
                } catch (e) {
                    console.error('解析最后一行数据出错:', e);
                }
            }
            
            // 确保在流式处理结束时移除思考动画
            if (isFirstChunk) {
                removeTypingAnimation(messageDiv);
                updateAIMessage(messageDiv, '处理完成');
            }
            
            cleanup();
            
        } catch (error) {
            console.error('请求错误:', error);
            updateStatus('请求失败', 'error');
            
            // 移除思考动画并显示错误消息
            if (messageDiv) {
                removeTypingAnimation(messageDiv);
                updateAIMessage(messageDiv, '抱歉，处理您的请求时出现了错误。请检查网络连接或稍后重试。');
            } else {
                addMessage('无法连接到AI服务，请检查网络连接或服务状态。', 'ai');
            }
            
            cleanup();
        }
    }
    
    // 解析流式数据
    function parseStreamData(dataString) {
        // 移除 "data:" 前缀
        if (dataString.startsWith('data:')) {
            dataString = dataString.substring(5);
        }
        
        // 清理数据字符串
        dataString = dataString.trim();
        
        try {
            return JSON.parse(dataString);
        } catch (e) {
            // 如果不是JSON，返回原始数据
            return { raw: dataString };
        }
    }
    
    // 显示流式数据
    function displayStreamData(data) {
        const streamItem = document.createElement('div');
        streamItem.className = 'stream-item';
        
        const timestamp = new Date().toLocaleTimeString();
        
        // 检查是否包含查询结果数据
        let hasQueryData = false;
        if (data && typeof data === 'object') {
            // 检查SqlExecuteNode格式
            if (data.node === "SqlExecuteNode" && data.data && data.data.data && data.data.data.records) {
                hasQueryData = true;
            } else {
                // 检查其他格式
                for (const key in data) {
                    if (Array.isArray(data[key]) && data[key].length > 0) {
                        const firstItem = data[key][0];
                        if (firstItem && typeof firstItem === 'object') {
                            const hasQueryFields = Object.keys(firstItem).some(field => 
                                field.includes('村') || field.includes('任务') || field.includes('完成') || 
                                field.includes('率') || field.includes('进度') || field.includes('得分')
                            );
                            if (hasQueryFields) {
                                hasQueryData = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
        
        streamItem.innerHTML = `
            <div class="stream-time">${timestamp}</div>
            <div class="stream-data ${hasQueryData ? 'has-query-data' : ''}">${JSON.stringify(data, null, 2)}</div>
            ${hasQueryData ? '<div class="query-data-indicator">🔍 包含查询结果数据</div>' : ''}
        `;
        
        streamContent.appendChild(streamItem);
        streamContent.scrollTop = streamContent.scrollHeight;
    }
    
    // 处理流式字段
    function processStreamFields(data, messageDiv = null) {
        console.log('处理流式字段:', data);
        
        // 更新信息面板
        if (data.databaseName) {
            databaseName.textContent = data.databaseName;
            console.log('更新数据库名:', data.databaseName);
        }
        if (data.businessTypes) {
            if (Array.isArray(data.businessTypes)) {
                businessTypes.textContent = data.businessTypes.join(', ');
            } else if (typeof data.businessTypes === 'string' && data.businessTypes.trim()) {
                businessTypes.textContent = data.businessTypes;
            }
            console.log('更新业务类型:', data.businessTypes);
        }
        if (data.isDataQuery !== undefined) {
            isDataQuery.textContent = data.isDataQuery ? '是' : '否';
            isDataQuery.className = data.isDataQuery ? 'info-value success' : 'info-value error';
            console.log('更新数据查询状态:', data.isDataQuery);
        }
        if (data.tableNames && Array.isArray(data.tableNames)) {
            tableCount.textContent = data.tableNames.length;
            console.log('更新表数量:', data.tableNames.length);
        }
        
        // 处理SQL
        if (data.sql) {
            currentSql += data.sql;
            updateSqlContent();
            console.log('更新SQL:', data.sql);
        }
        
        // 智能检测和处理数据
        detectAndProcessData(data);
        
        // 处理节点流程
        if (data.node) {
            processNode(data);
        }
        
        // 处理图表
        if (data.chart) {
            currentChart += data.chart;
            updateChartContent();
            console.log('更新图表:', data.chart);
        }
        
        // 如果有完整的回复数据，在聊天框中显示
        if (data.answer || (data.data && data.data.records) || data.chart || data.sql) {
            // 如果传入了messageDiv，使用它；否则查找最后一个AI消息
            let aiMessage = messageDiv || document.querySelector('.message.ai-message:last-child');
            
            if (!aiMessage || aiMessage.querySelector('.response-text')) {
                // 创建新的AI回复消息
                aiMessage = createAIResponseMessage(data);
            } else {
                // 更新现有消息
                updateAIMessage(aiMessage, data.answer || '正在处理您的请求...');
            }
        }
    }
    
    // 智能检测和处理数据
    function detectAndProcessData(data) {
        // 检查各种可能的数据结构
        let foundData = false;
        
        // 1. 检查SqlExecuteNode格式: data.node === "SqlExecuteNode" && data.data.data.records
        if (data.node === "SqlExecuteNode" && data.data && data.data.data && data.data.data.records) {
            currentData = data.data.data;
            updateDataContent();
            console.log('找到SqlExecuteNode格式数据:', data.data.data);
            foundData = true;
        }
        
        // 2. 直接的数据字段
        if (data.data && data.data.records) {
            currentData = data.data;
            updateDataContent();
            console.log('找到records数据:', data.data);
            foundData = true;
        }
        
        // 3. 数据字段直接是数组
        if (data.data && Array.isArray(data.data)) {
            currentData = { records: data.data };
            updateDataContent();
            console.log('找到数组数据:', data.data);
            foundData = true;
        }
        
        // 4. 检查是否有records字段
        if (data.records && Array.isArray(data.records)) {
            currentData = { records: data.records };
            updateDataContent();
            console.log('找到直接records数据:', data.records);
            foundData = true;
        }
        
        // 5. 检查整个数据对象是否包含查询结果
        if (data && typeof data === 'object') {
            // 查找包含数组的字段
            for (const key in data) {
                if (Array.isArray(data[key]) && data[key].length > 0) {
                    // 检查数组中的对象是否看起来像查询结果
                    const firstItem = data[key][0];
                    if (firstItem && typeof firstItem === 'object') {
                        // 检查是否包含常见的查询结果字段
                        const hasQueryFields = Object.keys(firstItem).some(field => 
                            field.includes('村') || field.includes('任务') || field.includes('完成') || 
                            field.includes('率') || field.includes('进度') || field.includes('得分')
                        );
                        
                        if (hasQueryFields) {
                            currentData = { records: data[key] };
                            updateDataContent();
                            console.log('找到查询结果数据:', data[key]);
                            foundData = true;
                            break;
                        }
                    }
                }
            }
        }
        
        if (!foundData) {
            console.log('未找到查询结果数据，数据结构:', data);
        }
    }
    
    // 处理节点流程
    function processNode(data) {
        const nodeName = data.node;
        const nodeData = data.data || {};
        const timestamp = new Date().toLocaleTimeString();
        
        // 更新当前节点
        currentNode = nodeName;
        
        // 检查节点是否已存在
        let existingNode = nodeFlow.find(node => node.name === nodeName);
        
        if (existingNode) {
            // 更新现有节点
            existingNode.data = nodeData;
            existingNode.timestamp = timestamp;
            existingNode.status = 'completed';
        } else {
            // 添加新节点
            const nodeInfo = getNodeInfo(nodeName);
            const newNode = {
                name: nodeName,
                displayName: nodeInfo.displayName,
                description: nodeInfo.description,
                icon: nodeInfo.icon,
                data: nodeData,
                timestamp: timestamp,
                status: nodeName === '__START__' ? 'completed' : 'processing'
            };
            
            nodeFlow.push(newNode);
        }
        
        // 更新节点显示
        updateNodesDisplay();
        console.log('处理节点:', nodeName, nodeData);
    }
    
    // 获取节点信息
    function getNodeInfo(nodeName) {
        const nodeMap = {
            '__START__': {
                displayName: '开始处理',
                description: 'AI开始分析用户查询',
                icon: 'fas fa-play'
            },
            'SemanticRouterNode': {
                displayName: '语义路由',
                description: '分析查询意图，确定处理路径',
                icon: 'fas fa-route'
            },
            'IntentIdentificationNode': {
                displayName: '意图识别',
                description: '识别查询类型和业务意图',
                icon: 'fas fa-brain'
            },
            'GetGoldenSqlNode': {
                displayName: '获取参考SQL',
                description: '查找相似的SQL查询模板',
                icon: 'fas fa-search'
            },
            'GetTableNamesNode': {
                displayName: '获取表名',
                description: '确定查询涉及的数据表',
                icon: 'fas fa-table'
            },
            'TableRelationNode': {
                displayName: '表关系分析',
                description: '分析表之间的关联关系',
                icon: 'fas fa-project-diagram'
            },
            'SqlGeneratorNode': {
                displayName: 'SQL生成',
                description: '根据分析结果生成SQL语句',
                icon: 'fas fa-code'
            },
            'SqlExecuteNode': {
                displayName: 'SQL执行',
                description: '执行SQL查询，获取数据结果',
                icon: 'fas fa-database'
            },
            'ChartGenerationNode': {
                displayName: '图表生成',
                description: '根据数据生成可视化图表',
                icon: 'fas fa-chart-bar'
            },
            '__END__': {
                displayName: '处理完成',
                description: 'AI处理流程结束',
                icon: 'fas fa-check'
            }
        };
        
        return nodeMap[nodeName] || {
            displayName: nodeName,
            description: '处理节点',
            icon: 'fas fa-cog'
        };
    }
    
    // 更新节点显示
    function updateNodesDisplay() {
        const nodesInfo = document.getElementById('nodesInfo');
        if (!nodesInfo) return;
        nodesInfo.innerHTML = `<span class="nodes-count">${nodeFlow.length} 个节点</span>`;
        
        if (nodeFlow.length === 0) {
            nodesContent.innerHTML = `
                <div class="nodes-placeholder">
                    <i class="fas fa-sitemap"></i>
                    <p>暂无处理流程数据</p>
                </div>
            `;
            return;
        }
        
        const nodesFlow = document.createElement('div');
        nodesFlow.className = 'nodes-flow';
        
        nodeFlow.forEach((node, index) => {
            const nodeItem = document.createElement('div');
            nodeItem.className = `node-item ${node.status}`;
            
            const iconClass = node.status === 'completed' ? 'completed' : 
                             node.status === 'processing' ? 'processing' : 'process';
            
            nodeItem.innerHTML = `
                <div class="node-icon ${iconClass}">
                    <i class="${node.icon}"></i>
                </div>
                <div class="node-content">
                    <div class="node-name">${node.displayName}</div>
                    <div class="node-description">${node.description}</div>
                    ${node.data && Object.keys(node.data).length > 0 ? `
                        <div class="node-details">
                            ${getNodeDetails(node.name, node.data)}
                        </div>
                    ` : ''}
                </div>
                <div class="node-time">${node.timestamp}</div>
                <div class="node-arrow"></div>
            `;
            
            nodesFlow.appendChild(nodeItem);
        });
        
        nodesContent.innerHTML = '';
        nodesContent.appendChild(nodesFlow);
    }
    
    // 获取节点详细信息
    function getNodeDetails(nodeName, data) {
        switch (nodeName) {
            case 'SemanticRouterNode':
                return `数据库: ${data.databaseName || '未知'}`;
            case 'IntentIdentificationNode':
                return `业务类型: ${data.businessTypes ? data.businessTypes.join(', ') : '未知'}`;
            case 'GetTableNamesNode':
                return `表数量: ${data.tableNames ? data.tableNames.length : 0}`;
            case 'SqlGeneratorNode':
                return `SQL已生成`;
            case 'SqlExecuteNode':
                return `查询结果: ${data.data && data.data.records ? data.data.records.length : 0} 条记录`;
            case 'ChartGenerationNode':
                return `图表已生成`;
            default:
                return Object.keys(data).length > 0 ? 
                    Object.keys(data).slice(0, 3).map(key => `${key}: ${data[key]}`).join(', ') : 
                    '处理中...';
        }
    }
    
    // 更新SQL内容
    function updateSqlContent() {
        if (currentSql) {
            sqlContent.innerHTML = `
                <div class="sql-code">
                    <pre><code>${currentSql}</code></pre>
                </div>
            `;
        }
    }
    
    // 更新数据内容
    function updateDataContent() {
        console.log('更新数据内容，currentData:', currentData);
        
        if (currentData && currentData.records) {
            const records = currentData.records;
            const dataInfo = document.getElementById('dataInfo');
            if (!dataInfo) return;
            dataInfo.innerHTML = `<span class="data-count">${records.length} 条记录</span>`;
            
            if (records.length > 0) {
                const table = createDataTable(records);
                dataContent.innerHTML = '';
                dataContent.appendChild(table);
                console.log('数据表格创建成功，记录数:', records.length);
            }
        } else {
            console.log('没有找到records数据，currentData结构:', currentData);
            // 尝试其他可能的数据结构
            if (currentData && Array.isArray(currentData)) {
                const dataInfo = document.getElementById('dataInfo');
                if (!dataInfo) return;
                dataInfo.innerHTML = `<span class="data-count">${currentData.length} 条记录</span>`;
                
                if (currentData.length > 0) {
                    const table = createDataTable(currentData);
                    dataContent.innerHTML = '';
                    dataContent.appendChild(table);
                    console.log('使用数组格式创建表格，记录数:', currentData.length);
                }
            }
        }
    }
    
    // 创建数据表格
    function createDataTable(records) {
        const table = document.createElement('table');
        table.className = 'data-table';
        
        if (records.length > 0) {
            // 创建表头
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');
            const headers = Object.keys(records[0]);
            headers.forEach(header => {
                const th = document.createElement('th');
                th.textContent = header;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            table.appendChild(thead);
            
            // 创建表体
            const tbody = document.createElement('tbody');
            records.forEach(record => {
                const row = document.createElement('tr');
                headers.forEach(header => {
                    const td = document.createElement('td');
                    td.textContent = record[header] || '-';
                    row.appendChild(td);
                });
                tbody.appendChild(row);
            });
            table.appendChild(tbody);
        }
        
        return table;
    }
    
    // 更新图表内容
    function updateChartContent() {
        if (currentChart) {
            try {
                // 检测JSON格式的图表配置
                const jsonMatch = currentChart.match(/```json\s*(\{[\s\S]*?\})\s*```/);
                if (jsonMatch) {
                    const chartConfig = JSON.parse(jsonMatch[1]);
                    renderChart(chartConfig);
                } else {
                    // 尝试直接解析JSON
                    const chartConfig = JSON.parse(currentChart);
                    renderChart(chartConfig);
                }
            } catch (e) {
                console.error('图表解析失败:', e);
                // 显示原始图表数据
                chartContent.innerHTML = `
                    <div class="chart-raw-data">
                        <h4>图表数据:</h4>
                        <pre>${currentChart}</pre>
                    </div>
                `;
            }
        }
    }
    
    // 渲染图表
    function renderChart(config) {
        console.log('渲染图表配置:', config);
        
        // 清空图表容器
        chartContent.innerHTML = '';
        
        // 创建图表容器
        const chartContainer = document.createElement('div');
        chartContainer.className = 'chart-container loading';
        chartContainer.style.width = '100%';
        chartContainer.style.height = '500px';
        
        chartContent.appendChild(chartContainer);
        
        // 延迟渲染，确保容器已准备好
        setTimeout(() => {
            try {
                // 移除加载状态
                chartContainer.classList.remove('loading');
                
                // 初始化图表
                const chart = echarts.init(chartContainer);
                
                // 优化图表配置
                const optimizedConfig = optimizeChartConfig(config);
                console.log('优化后的图表配置:', optimizedConfig);
                
                // 设置配置并渲染
                chart.setOption(optimizedConfig, true); // 第二个参数为true表示不合并配置
                
                // 存储图表实例
                const chartId = Date.now() + Math.random();
                chartInstances.set(chartId, chart);
                
                // 监听窗口大小变化
                const resizeHandler = () => {
                    chart.resize();
                };
                window.addEventListener('resize', resizeHandler);
                
                // 存储resize处理器，用于清理
                chart._resizeHandler = resizeHandler;
                
                console.log('图表渲染成功');
            } catch (e) {
                console.error('图表渲染失败:', e);
                chartContainer.innerHTML = `
                    <div class="chart-error">
                        <h4><i class="fas fa-exclamation-triangle"></i> 图表渲染失败</h4>
                        <p><strong>错误信息:</strong> ${e.message}</p>
                        <details style="margin-top: 15px;">
                            <summary>查看原始配置</summary>
                            <pre style="margin-top: 10px; background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto;">${JSON.stringify(config, null, 2)}</pre>
                        </details>
                    </div>
                `;
            }
        }, 100);
    }
    
    // 优化图表配置
    function optimizeChartConfig(config) {
        const optimized = JSON.parse(JSON.stringify(config)); // 深拷贝
        
        // 设置基础配置
        optimized.animation = true;
        optimized.animationDuration = 1000;
        optimized.animationEasing = 'cubicOut';
        
        // 优化标题
        if (optimized.title) {
            optimized.title.textStyle = {
                fontSize: 16,
                fontWeight: 'bold',
                color: '#2c3e50'
            };
            optimized.title.left = 'center';
            optimized.title.top = 20;
        }
        
        // 优化图例
        if (optimized.legend) {
            optimized.legend = {
                ...optimized.legend,
                top: 50,
                left: 'center',
                orient: 'horizontal',
                textStyle: {
                    fontSize: 12
                },
                itemGap: 20
            };
        }
        
        // 优化X轴
        if (optimized.xAxis) {
            if (Array.isArray(optimized.xAxis)) {
                optimized.xAxis.forEach(axis => optimizeXAxis(axis));
            } else {
                optimizeXAxis(optimized.xAxis);
            }
        }
        
        // 优化Y轴
        if (optimized.yAxis) {
            if (Array.isArray(optimized.yAxis)) {
                optimized.yAxis.forEach(axis => optimizeYAxis(axis));
            } else {
                optimizeYAxis(optimized.yAxis);
            }
        }
        
        // 优化系列
        if (optimized.series) {
            optimized.series.forEach(series => optimizeSeries(series));
        }
        
        // 优化工具提示
        if (!optimized.tooltip) {
            optimized.tooltip = {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                backgroundColor: 'rgba(0,0,0,0.8)',
                textStyle: {
                    color: '#fff'
                }
            };
        }
        
        // 优化网格
        optimized.grid = {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '20%',
            containLabel: true
        };
        
        return optimized;
    }
    
    // 优化X轴配置
    function optimizeXAxis(axis) {
        if (axis.type === 'category') {
            axis.axisLabel = {
                ...axis.axisLabel,
                rotate: 45, // 设置旋转角度
                interval: 0, // 显示所有标签
                fontSize: 11,
                color: '#666',
                margin: 15
            };
            axis.axisTick = {
                alignWithLabel: true
            };
        }
    }
    
    // 优化Y轴配置
    function optimizeYAxis(axis) {
        axis.axisLabel = {
            ...axis.axisLabel,
            fontSize: 11,
            color: '#666'
        };
        axis.axisLine = {
            show: true,
            lineStyle: {
                color: '#ddd'
            }
        };
        axis.splitLine = {
            show: true,
            lineStyle: {
                color: '#f0f0f0',
                type: 'dashed'
            }
        };
    }
    
    // 优化系列配置
    function optimizeSeries(series) {
        // 优化柱状图
        if (series.type === 'bar') {
            series.barWidth = '60%';
            series.itemStyle = {
                ...series.itemStyle,
                borderRadius: [4, 4, 0, 0]
            };
            series.label = {
                show: false // 默认不显示标签，避免重叠
            };
        }
        
        // 优化折线图
        if (series.type === 'line') {
            series.smooth = true;
            series.symbol = 'circle';
            series.symbolSize = 6;
            series.lineStyle = {
                width: 2
            };
            series.label = {
                show: false // 默认不显示标签，避免重叠
            };
        }
        
        // 优化饼图
        if (series.type === 'pie') {
            series.radius = ['40%', '70%'];
            series.center = ['50%', '60%'];
            series.label = {
                show: true,
                formatter: '{b}: {c} ({d}%)',
                fontSize: 11
            };
            series.labelLine = {
                show: true,
                length: 15,
                length2: 10
            };
        }
    }
    
    // 创建AI消息
    function createAIMessage() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ai-message';
        messageDiv.innerHTML = `
            <div class="message-content">
                <i class="fas fa-robot message-icon"></i>
                <div class="message-text"></div>
            </div>
        `;
        chatMessages.appendChild(messageDiv);
        return messageDiv;
    }
    
    // 更新AI消息
    function updateAIMessage(messageDiv, text) {
        const messageText = messageDiv.querySelector('.message-text');
        messageText.textContent = text;
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    // 追加内容到AI消息
    function appendToAIMessage(messageDiv, text) {
        const messageText = messageDiv.querySelector('.message-text');
        
        // 添加流式输出样式
        messageText.classList.add('streaming');
        
        // 追加文本
        messageText.textContent += text;
        
        // 滚动到底部
        chatMessages.scrollTop = chatMessages.scrollHeight;
        
        // 短暂延迟后移除流式样式（模拟打字效果）
        setTimeout(() => {
            messageText.classList.remove('streaming');
        }, 100);
    }
    
    // 添加打字动画
    function addTypingAnimation(messageDiv) {
        // 如果已经有动画在进行，先移除
        if (currentTypingAnimation) {
            removeTypingAnimation(currentTypingAnimation);
        }
        
        const messageText = messageDiv.querySelector('.message-text');
        messageText.classList.add('typing-animation', 'thinking');
        
        // 添加打字点动画
        const typingDots = document.createElement('span');
        typingDots.className = 'typing-dots';
        typingDots.innerHTML = '<span>.</span><span>.</span><span>.</span>';
        messageText.appendChild(typingDots);
        
        // 记录当前动画
        currentTypingAnimation = messageDiv;
    }
    
    // 移除打字动画
    function removeTypingAnimation(messageDiv) {
        if (!messageDiv) return;
        
        const messageText = messageDiv.querySelector('.message-text');
        if (!messageText) return;
        
        messageText.classList.remove('typing-animation');
        
        // 移除打字点
        const typingDots = messageText.querySelector('.typing-dots');
        if (typingDots) {
            typingDots.remove();
        }
        
        // 移除思考状态
        messageText.classList.remove('thinking');
        
        // 如果内容只是"正在思考..."，清空它
        if (messageText.textContent.trim() === '正在思考...') {
            messageText.textContent = '';
        }
        
        // 清除当前动画记录
        if (currentTypingAnimation === messageDiv) {
            currentTypingAnimation = null;
        }
    }
    
    // 创建AI回复消息（包含结构化内容）
    function createAIResponseMessage(data) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ai-message';
        
        let content = '';
        
        // 添加基本回复文本
        if (data.answer) {
            content += `<div class="response-text">${data.answer}</div>`;
        }
        
        // 添加数据预览
        if (data.data && data.data.records && data.data.records.length > 0) {
            const records = data.data.records;
            const previewCount = Math.min(3, records.length);
            const previewData = records.slice(0, previewCount);
            
            content += `
                <div class="data-preview">
                    <h4><i class="fas fa-table"></i> 查询结果预览 (${records.length} 条记录)</h4>
                    <div class="data-summary">
                        <div class="summary-info">
                            <div class="info-item">
                                <span class="info-label">数据库:</span>
                                <span class="info-value">${data.databaseName || '未知'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">业务类型:</span>
                                <span class="info-value">${data.businessTypes ? data.businessTypes.join(', ') : '未知'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">数据查询:</span>
                                <span class="info-value">${data.isDataQuery ? '是' : '否'}</span>
                            </div>
                        </div>
                    </div>
                    <div class="data-table-preview">
                        <table style="width: 100%; font-size: 0.8rem; border-collapse: collapse;">
                            <thead>
                                <tr style="background: #f8f9fa;">
                                    ${Object.keys(previewData[0]).map(key => `<th style="padding: 8px; border: 1px solid #dee2e6;">${key}</th>`).join('')}
                                </tr>
                            </thead>
                            <tbody>
                                ${previewData.map(record => `
                                    <tr>
                                        ${Object.values(record).map(value => `<td style="padding: 8px; border: 1px solid #dee2e6;">${value}</td>`).join('')}
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                        ${records.length > 3 ? `<p style="text-align: center; margin-top: 10px; color: #666;">... 还有 ${records.length - 3} 条记录，查看右侧"查询结果"标签页</p>` : ''}
                    </div>
                </div>
            `;
        }
        
        // 添加图表预览
        if (data.chart) {
            content += `
                <div class="chart-preview">
                    <h4><i class="fas fa-chart-bar"></i> 数据图表</h4>
                    <p>已生成可视化图表，查看右侧"图表"标签页查看详细内容</p>
                </div>
            `;
        }
        
        // 添加SQL预览
        if (data.sql) {
            content += `
                <div class="sql-preview">
                    <h4><i class="fas fa-code"></i> 执行的SQL语句</h4>
                    <pre>${data.sql}</pre>
                </div>
            `;
        }
        
        messageDiv.innerHTML = `
            <div class="message-content">
                <i class="fas fa-robot message-icon"></i>
                <div class="message-text">${content}</div>
            </div>
        `;
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        return messageDiv;
    }
    
    // 添加消息
    function addMessage(text, sender) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}-message`;
        
        if (sender === 'user') {
            messageDiv.innerHTML = `
                <div class="message-content">
                    <div class="message-text">${text}</div>
                    <i class="fas fa-user message-icon"></i>
                </div>
            `;
        } else {
            messageDiv.innerHTML = `
                <div class="message-content">
                    <i class="fas fa-robot message-icon"></i>
                    <div class="message-text">${text}</div>
                </div>
            `;
        }
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    // 清空所有内容
    function clearAllContent() {
        streamContent.innerHTML = '<div class="stream-placeholder"><i class="fas fa-wave-square"></i><p>等待数据流...</p></div>';
        nodesContent.innerHTML = '<div class="nodes-placeholder"><i class="fas fa-sitemap"></i><p>暂无处理流程数据</p></div>';
        dataContent.innerHTML = '<div class="data-placeholder"><i class="fas fa-database"></i><p>暂无查询结果</p></div>';
        chartContent.innerHTML = '<div class="chart-placeholder"><i class="fas fa-chart-line"></i><p>暂无图表数据</p></div>';
        sqlContent.innerHTML = '<div class="sql-placeholder"><i class="fas fa-terminal"></i><p>暂无SQL语句</p></div>';
        
        currentData = null;
        currentSql = '';
        currentChart = null;
        nodeFlow = [];
        currentNode = null;
        
        // 清空信息面板
        databaseName.textContent = '-';
        businessTypes.textContent = '-';
        isDataQuery.textContent = '-';
        isDataQuery.className = 'info-value';
        tableCount.textContent = '-';
    }
    
    // 更新状态
    function updateStatus(text, type) {
        const statusText = statusIndicator.querySelector('.status-text');
        const statusDot = statusIndicator.querySelector('.status-dot');
        
        statusText.textContent = text;
        statusIndicator.className = `status-indicator ${type}`;
    }
    
    // 清理资源
    function cleanup() {
        isProcessing = false;
        sendButton.disabled = false;
        updateStatus('就绪', 'ready');
        
        // 清理动画状态
        if (currentTypingAnimation) {
            removeTypingAnimation(currentTypingAnimation);
        }
    }
    
    // 显示通知
    function showNotification(message, type) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
    
    // 事件监听
    sendButton.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    
    // 页面卸载前清理（如果需要的话）
    window.addEventListener('beforeunload', function() {
        // 清理资源
    });
});
